package br.com.gaacorp.sai.webapp.action;

import java.io.Serializable;

import br.com.gaacorp.sai.model.Alternative;
import br.com.gaacorp.sai.webapp.action.BasePage;
import br.com.gaacorp.sai.service.GenericManager;

public class AlternativeForm extends BasePage implements Serializable {
    private GenericManager<Alternative, Long> alternativeManager;
    private Alternative alternative = new Alternative();
    private Long alternativeId;

    public void setAlternativeManager(GenericManager<Alternative, Long> alternativeManager) {
        this.alternativeManager = alternativeManager;
    }

    public Alternative getAlternative() {
        return alternative;
    }

    public void setAlternative(Alternative alternative) {
        this.alternative = alternative;
    }

    public void setAlternativeId(Long alternativeId) {
        this.alternativeId = alternativeId;
    }

    public String delete() {
        alternativeManager.remove(alternative.getAlternativeId());
        addMessage("alternative.deleted");

        return "alternativeList";
    }

    public String edit() {
        // Comparison to zero (vs. null) is required with MyFaces 1.2.2, not with previous versions
        if (alternativeId != null && alternativeId != 0) {
            alternative = alternativeManager.get(alternativeId);
        } else {
            alternative = new Alternative();
        }

        return "alternativeForm";
    }

    public String save() {
        boolean isNew = (alternative.getAlternativeId() == null || alternative.getAlternativeId() == 0);
        alternativeManager.save(alternative);

        String key = (isNew) ? "alternative.added" : "alternative.updated";
        addMessage(key);

        if (isNew) {
            return "alternativeList";
        } else {
            return "alternativeForm";
        }
    }
} 